<template>
  <Teleport to="body">
    <Transition name="modal" appear>
      <div v-if="isVisible" class="modal-overlay" @click="handleOverlayClick">
        <div class="modal-container" :class="{ 'mobile-fullscreen': isMobile }" @click.stop>
          <div class="modal-content">
            <div class="login-content">
              <div class="flex justify-center">
                <logo />
              </div>

              <!-- 邮箱输入步骤 -->
              <div v-if="step === 1" class="mt-[40px]">
                <div class="step-header">
                  <div class="step-title">Enter your email to continue</div>
                  <p class="step-subtitle">
                    An account will be automatically created for new users.
                  </p>
                </div>

                <div class="form-section">
                  <div class="form-group">
                    <label class="form-label">Email address</label>
                    <el-input
                      v-model="email"
                      placeholder="Enter your Email address"
                      type="email"
                      size="large"
                      class="email-input"
                      :class="{ 'is-error': emailError }"
                      @input="clearEmailError"
                      @keyup.enter="handleGetVerificationCode" />
                    <div v-if="emailError" class="error-message">
                      {{ emailError }}
                    </div>
                  </div>

                  <el-button
                    type="primary"
                    size="large"
                    :loading="isLoading"
                    :disabled="!isEmailValid || isLoading"
                    @click="handleGetVerificationCode"
                    class="w-full h-[48px] text-base font-medium"
                    style="border-radius: 30px">
                    <span v-if="!isLoading" class="get_code_text">Get Verification Code</span>
                  </el-button>
                </div>

                <!-- 协议条款 -->
                <div class="agreement-section agreement_view">
                  <div @click="agreed = !agreed" class="mr-[4px]">
                    <AgreeIcon :agreed="agreed" />
                  </div>
                  <p class="agreement-text ml-[4px]">
                    By continuing, you agree to our
                    <span class="color_text cursor-pointer" @click="goTerms">Terms of Service</span>
                    and
                    <span class="color_text cursor-pointer" @click="goPrivacy">Privacy Policy</span>
                  </p>
                </div>
              </div>

              <!-- 验证码输入步骤 -->
              <div v-else-if="step === 2" class="mt-[40px]">
                <div class="step-header">
                  <h2 class="step-title">Verify your email</h2>
                  <p class="step-subtitle">Enter the verification code sent to your email</p>
                  <div @click="step = 1" class="email-display">
                    <span class="email_text cursor-pointer">{{ email }}</span>
                    <EditIcon class="ml-[3px]" />
                  </div>
                </div>

                <div class="form-section">
                  <VerificationCodeInput
                    v-model="verificationCode"
                    :error="codeError"
                    :isLogin="isLogin"
                    @complete="handleVerifyCode" />

                  <!-- 倒计时显示 -->
                  <div class="countdown-text mt-[20px]">
                    <span class="cursor-pointer email_text" @click="handleResendCode">
                      Didn't receive a code?
                    </span>
                    <span class="cursor-pointer email_text" @click="handleResendCode">Resend</span>
                    <span v-if="countdown > 0">({{ countdown }})</span>
                  </div>
                </div>
              </div>

              <!-- 谷歌登录 -->
              <div>
                <div class="py-[8px]">
                  <el-divider content-position="center">Or</el-divider>
                </div>

                <button
                  class="google-btn w-full"
                  @click="loginWithGoogle"
                  :disabled="isGoogleLoading">
                  <img
                    src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg"
                    alt="google" />
                  {{ isGoogleLoading ? 'Login...' : 'Continue with Google' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
    <AgreeModal v-if="showAgreeModal" @cancel="showAgreeModal = false" @agree="agreeAgreeModal" />
  </Teleport>
</template>

<script setup lang="ts">
  import Logo from '@/components/icons/logo.vue';
  import { ref, computed, onUnmounted, watch, onMounted } from 'vue';
  import { Close, Edit } from '@element-plus/icons-vue';
  import VerificationCodeInput from '@/components/VerificationCodeInput.vue';
  import { useLoginModalStore } from '@/store/loginModal';
  import { useUserStore } from '@/store/user';
  import { UserAPI } from '@/api/user';
  import type { LoginFormData, LoginStep } from '@/types/login';
  import { useRouter } from 'vue-router';
  import EditIcon from '@/components/icons/EditIcon.vue';
  import AgreeIcon from '@/components/icons/AgreeIcon.vue';
  import AgreeModal from '@/components/AgreeModal.vue';
  import { useGoogleLogin } from '@/composables/useGoogleLogin';
  const router = useRouter();
  // 使用 store
  const loginModalStore = useLoginModalStore();
  const userStore = useUserStore();

  const { loginWithGoogle, isGoogleLoading } = useGoogleLogin();

  // 响应式数据
  const email = ref('');
  const verificationCode = ref('');
  const emailError = ref('');
  const codeError = ref('');
  const agreed = ref(false);
  const step = ref<1 | 2>(1);
  const countdown = ref(0);
  const showAgreeModal = ref<boolean>(false); // 隐私协议modal
  const isLogin = ref(false);

  // 计算属性
  const isVisible = computed(() => loginModalStore.visible);
  const isLoading = computed(() => loginModalStore.loading);

  const isEmailValid = computed(() => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email.value);
  });

  const isMobile = computed(() => {
    return window.innerWidth <= 768;
  });

  // 定时器
  let countdownTimer: any = null;

  // 监听弹窗显示状态，重置表单
  watch(isVisible, (visible) => {
    if (visible) {
      resetForm();
    }
  });

  // 隐私协议modal
  const agreeAgreeModal = () => {
    showAgreeModal.value = false;
    agreed.value = true;
    handleGetVerificationCode();
  };

  // 方法
  const resetForm = () => {
    email.value = '';
    verificationCode.value = '';
    emailError.value = '';
    codeError.value = '';
    agreed.value = false;
    step.value = 1;
    countdown.value = 0;
    if (countdownTimer) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
  };

  const clearEmailError = () => {
    emailError.value = '';
  };

  const validateEmail = () => {
    if (!email.value) {
      emailError.value = 'Please enter your email address';
      return false;
    }
    if (!isEmailValid.value) {
      emailError.value = 'Please enter a valid email address';
      return false;
    }
    return true;
  };

  const startCountdown = () => {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
    countdown.value = 60;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer!);
        countdownTimer = null;
      }
    }, 1000);
  };

  const handleGetVerificationCode = async () => {
    if (!validateEmail()) return;

    // 检查协议是否同意
    if (!agreed.value) {
      showAgreeModal.value = true;
      return;
    }

    loginModalStore.setLoading(true);
    emailError.value = '';
    verificationCode.value = '';
    try {
      // 调用真实API获取验证码
      await UserAPI.getCode({
        email: email.value,
      });

      step.value = 2;
      startCountdown();
    } catch (error: any) {
      console.error('Send verification code error:', error);
    } finally {
      loginModalStore.setLoading(false);
    }
  };

  const handleVerifyCode = async (code?: string) => {
    const codeToVerify = code || verificationCode.value;

    if (!codeToVerify || codeToVerify.length !== 6) {
      codeError.value = 'Please enter a complete 6-digit code';
      return;
    }

    loginModalStore.setLoading(true);
    codeError.value = '';

    try {
      // 调用真实API进行登录
      const res = await UserAPI.login({
        email: email.value,
        code: codeToVerify,
        source_type: 1,
      });

      console.log('登录响应:', res);

      // 存储用户信息到store（自动持久化）
      // 注意：这里需要根据实际API返回结构调整
      userStore.loginSuccess(res);

      isLogin.value = true;
      setTimeout(() => {
        loginModalStore.handleLoginSuccess();
      }, 500);
    } catch (error: any) {
      codeError.value = 'Incorrect code';
      console.error('Verify code error:', error);
    } finally {
      loginModalStore.setLoading(false);
    }
  };

  const handleResendCode = async () => {
    if (countdown.value > 0) return;
    await UserAPI.getCode({
      email: email.value,
    });
    startCountdown();
  };

  const goTerms = () => {
    router.push('/terms');
  };

  const goPrivacy = () => {
    router.push('/privacy');
  };

  const handleClose = () => {
    loginModalStore.hideModal();
  };

  const handleOverlayClick = () => {
    handleClose();
  };

  // 键盘事件处理
  const handleKeydown = (event: KeyboardEvent) => {
    if (event.key === 'Escape' && isVisible.value) {
      handleClose();
    }
  };

  // 滚动锁定
  const lockScroll = () => {
    document.body.style.overflow = 'hidden';
  };

  const unlockScroll = () => {
    document.body.style.overflow = '';
  };

  // 监听弹窗显示状态
  watch(isVisible, (visible) => {
    if (visible) {
      lockScroll();
      document.addEventListener('keydown', handleKeydown);
    } else {
      unlockScroll();
      document.removeEventListener('keydown', handleKeydown);
    }
  });

  // 清理定时器和事件监听
  onUnmounted(() => {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
    document.removeEventListener('keydown', handleKeydown);
    unlockScroll();
  });
</script>

<style lang="scss" scoped>
  .agree_content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .agree_view {
    width: 440px;
    background: #fff;
    padding: 32px;
    border-radius: 16px;
    //position: absolute;
    //top: 50%; /* 顶部距离父容器 50% */
    //left: 50%; /* 左侧距离父容器 50% */
    //transform: translate(-50%, -50%); /* 向左、上偏移自身 50% */
    z-index: 300000;
    .title {
      color: var(---9, #0a0a0a);
      font-family: 'Inter Tight';
      font-size: 24px;
      font-style: normal;
      font-weight: 700;
      line-height: normal;
    }
    .des_text {
      color: var(---6, #7a7a7a);
      text-align: center;
      font-family: 'Inter Tight';
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: 150%; /* 24px */
    }
  }
  .agreement_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .email_text {
    color: #7a7a7a !important;
    font-size: 16px;
  }
  .email_text:hover {
    color: #0a0a0a !important;
    text-decoration: underline;
  }
  // 遮罩层
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    padding: 20px;
  }

  // 弹窗容器
  .modal-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    max-width: 568px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;

    &.mobile-fullscreen {
      max-width: none;
      width: 100vw;
      height: 100vh;
      border-radius: 0;
      max-height: none;
    }
  }

  // 弹窗内容
  .modal-content {
    padding: 40px 64px;

    .mobile-fullscreen & {
      padding: 20px;
    }
  }

  // 关闭按钮
  .modal-header {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;

    .close-btn {
      cursor: pointer;
      color: #7a7a7a;
      transition: color 0.3s ease;

      &:hover {
        color: #f76b1b;
      }
    }
  }

  // 登录内容样式已通过内联样式设置

  // 动画效果
  .modal-enter-active,
  .modal-leave-active {
    transition: all 0.3s ease;
  }

  .modal-enter-from,
  .modal-leave-to {
    opacity: 0;
  }

  .modal-enter-from .modal-container,
  .modal-leave-to .modal-container {
    transform: scale(0.9) translateY(-20px);
  }

  .modal-enter-to .modal-container,
  .modal-leave-from .modal-container {
    transform: scale(1) translateY(0);
  }

  .step-header {
    text-align: center;
    margin-bottom: 32px;

    .step-title {
      font-size: 32px;
      font-weight: 700;
      color: #0a0a0a;
      margin: 0 0 12px 0;
    }

    .step-subtitle {
      color: #7a7a7a;
      font-size: 16px;
      margin-top: 14px;
    }

    .email-display {
      display: flex;
      align-items: center;
      justify-content: center;

      .edit-icon {
        cursor: pointer;
        transition: color 0.3s ease;

        &:hover {
          color: #f76b1b;
        }
      }
    }
  }

  .form-section {
    margin-bottom: 40px;
  }

  .form-group {
    margin-bottom: 24px;

    .form-label {
      display: block;
      font-size: 14px;
      color: #0a0a0a;
      margin-bottom: 8px;
    }
  }

  .email-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      border: none;
      box-shadow: none;
      transition: all 0.3s ease;
      background: #f4f5f7;
      height: 48px;

      &:hover {
        border-color: #f76b1b;
      }

      &.is-focus {
        border-color: #f76b1b;
        box-shadow: 0 0 0 2px rgba(247, 107, 27, 0.1);
      }
    }

    &.is-error :deep(.el-input__wrapper) {
      border-color: #f56565;
      box-shadow: 0 0 0 2px rgba(245, 101, 101, 0.1);
    }
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    border-radius: 30px;
    font-size: 16px;
    font-weight: 700;
    background-color: #cbcbcb;
    cursor: pointer;
    color: #fff;

    :deep(.el-button) {
      background: #f76b1b;
      border-color: #f76b1b;

      &:hover {
        background: #e55a0f;
        border-color: #e55a0f;
      }

      &:disabled {
        background: #cbcbcb;
        border-color: #cbcbcb !important;
        color: #fff;
      }
    }
  }

  .agreement-section {
    text-align: center;

    .agreement-text {
      font-size: 14px;
      color: #7a7a7a;
      line-height: 1.5;
      margin: 0;

      .link {
        color: #f76b1b;
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }

  .countdown-text {
    text-align: center;
    color: #7a7a7a;
    font-size: 14px;
    //margin-top: 24px;
  }

  .error-message {
    color: #f56565;
    font-size: 12px;
    margin-top: 8px;
  }

  // 协议勾选框警告样式
  :deep(.el-checkbox) {
    &.agreement-warning {
      .el-checkbox__input {
        .el-checkbox__inner {
          border-color: #f56565 !important;
          background-color: #fef2f2 !important;
          animation: shake 0.5s ease-in-out;
        }
      }
    }
  }

  :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;

    &.el-button--primary {
      background: #f76b1b;
      border-color: #f76b1b;

      &:hover {
        background: #e55a0f;
        border-color: #e55a0f;
      }

      &:disabled {
        background: #e0e0e0;
        border-color: #e0e0e0;
        color: #9ca3af;
      }
    }
  }

  // 抖动动画
  @keyframes shake {
    0%,
    100% {
      transform: translateX(0);
    }

    10%,
    30%,
    50%,
    70%,
    90% {
      transform: translateX(-3px);
    }

    20%,
    40%,
    60%,
    80% {
      transform: translateX(3px);
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .login-content {
      padding: 16px;
    }

    .step-header {
      .step-title {
        font-size: 20px;
      }
    }
  }
  .get_code_text {
    color: var(---0, #fff);
    font-family: 'Inter Tight';
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
  }
  .color_text {
    color: #f76b1b;
    border-bottom: 1px solid #f76b1b;
    padding-bottom: 1px;
  }
  .color_text:hover {
    color: #e55c0d;
    border-bottom: 1px solid #e55c0d;
  }

  .google-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    width: 100%;
    height: 48px;
    padding: 0 24px;
    border-radius: 30px;
    background: #fff;
    color: #7a7a7a;
    font-size: 16px;
    background-color: #f4f5f7;
    font-weight: 500;
    font-family: 'Inter Tight';
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover:not(:disabled) {
      background: #f8f9fa;
    }

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    img {
      width: 20px;
      height: 20px;
    }
  }
</style>
